package com.liuhuan.controller;

import com.liuhuan.vo.CrudVo;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RestController;
import com.liuhuan.utils.Main;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.*;
/**
 * @version 1.0
 * @Author liuhuan
 * @Date 2024/7/9 10:48
 * @Crud代码生成器
 */

@RestController
@Api(tags = "Crud生成器")
@RequestMapping("/chat")
public class ChatController {

    private static final JSONArray messages = new JSONArray();

    static {
        // 定义系统消息system_message并添加到messages中
        JSONObject system_message = new JSONObject();
        system_message.put("role", "system");
        system_message.put("content", "你是刘欢同学研发的代码助手,只能生成java的crud代码，不要回答其他问题!");
        messages.put(system_message);
    }

    @PostMapping("/send")
    public String sendMessage(@RequestParam String content) {
        try {
            String userInput = content;
            // 定义用户消息user_message并添加到messages中
            JSONObject user_message = new JSONObject();
            user_message.put("role", "user");
            user_message.put("content", userInput);
            messages.put(user_message);

            // 定义传入的body对象
            JSONObject body = new JSONObject();
            // 定义body中的input对象
            JSONObject input_message = new JSONObject();
            input_message.put("messages", messages);
            // 定义body中的parameters对象
            JSONObject parameters_message = new JSONObject();
            parameters_message.put("result_format", "message");
            // 将model、input与parameters传入body中
            body.put("model", "qwen-turbo");
            body.put("input", input_message);
            body.put("parameters", parameters_message);

            // 进行模型的调用
            JSONObject assistant_output = Main.get_response(body);
            // 取出content并返回
            JSONObject output = assistant_output.getJSONObject("output");
            JSONArray choices = output.getJSONArray("choices");
            JSONObject firstChoice = choices.getJSONObject(0);
            JSONObject assistant_message = firstChoice.getJSONObject("message");
            String content1 = assistant_message.getString("content");

            // 将assistant_message添加到messages中
            messages.put(assistant_message);

            // 返回最新的模型输出
            return content1;

        } catch (Exception e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }


    @RequestMapping("/clear")
    public void ClearMessage(){
        messages.clear();
    }
}

